package com.intelligent.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.intelligent.mapper.ProductionTasksMapper;
import com.intelligent.pojo.ProductionTasks;
import com.intelligent.service.ProductionTasksService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

/**
* 针对表【production_tasks(生产任务表)】的数据库操作Service实现
*/
@Service
public class ProductionTasksServiceImpl extends ServiceImpl<ProductionTasksMapper, ProductionTasks>
    implements ProductionTasksService {

    @Override
    public IPage<Map<String, Object>> pageWithJoin(Page<?> page, Map<String, Object> params) {
        return this.baseMapper.selectPageWithJoin(page, params);
    }

    @Override
    public Map<String, Object> getByIdWithJoin(Long id) {
        if (id == null) {
            return null;
        }
        return this.baseMapper.selectByIdWithJoin(id);
    }

    @Override
    public int createTask(Map<String, Object> params) {
        if (params == null) {
            params = new HashMap<>();
        }
        // 任务编号自动生成：PT + yyyyMMddHHmmssSSS + 3位随机数
        String taskNo = generateTaskNo();
        params.put("taskNo", taskNo);
        // id 让数据库自增：传入 null 即可
        if (!params.containsKey("id")) {
            params.put("id", null);
        }
        return this.baseMapper.insertTask(params);
    }

    @Override
    public int updateTask(Map<String, Object> params) {
        if (params == null || params.get("id") == null) {
            return 0;
        }
        return this.baseMapper.updateTask(params);
    }

    @Override
    public int deleteTaskById(Long id) {
        if (id == null) {
            return 0;
        }
        return this.baseMapper.deleteTaskById(id);
    }

    private String generateTaskNo() {
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        String ts = LocalDateTime.now(ZoneId.of("Asia/Shanghai")).format(fmt);
        int rand = ThreadLocalRandom.current().nextInt(100, 1000);
        return "PT" + ts + rand;
    }
}
